<template>
  <div class="container">
    <div class="article">
      <el-form :model="articleForm" :rules="rules" ref="articleForm" label-width="100px" class="demo-articleForm">
        <el-form-item label="文章名称" prop="title">
          <el-input v-model.trim="articleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="文章封面">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :http-request="addCover"
            :before-upload="beforeUpload"
          >
            <img v-if="articleForm.cover" :src="articleForm.cover" width="80px" height="60px" alt="文章封面" />
            <i class="iconfont icon-tianjia-daohang" v-if="!articleForm.cover"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章类型" prop="category">
          <el-select v-model="articleForm.category" placeholder="请选择" size="mini">
            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否为草稿" prop="is_draft">
          <el-select v-model="articleForm.is_draft" size="mini" placeholder="请选择">
            <el-option
              v-for="item in is_draftOptions"
              :key="item.key"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用markdown：" label-width="150px">
          <el-radio v-model="articleForm.is_markdown" :label="true" :disabled="type === 'edit'">是</el-radio>
          <el-radio v-model="articleForm.is_markdown" :label="false" :disabled="type === 'edit'">否</el-radio>
        </el-form-item>
        <el-form-item label="文章地址" v-if="articleForm.is_markdown && type === 'add'">
          <el-input v-model="address" style="width: 400px"></el-input>
          <el-button class="btn" type="primary" @click="getArticle">获取文章</el-button>
          <span class="fz12">(支持csdn 掘金 简书 知乎)</span>
        </el-form-item>
        <el-form-item label="文章内容:">
          <!-- 引入markdown编辑器 -->
          <MyMarkdownEditor v-model="articleForm.content" v-if="articleForm.is_markdown" />
          <!-- 引入富文本编辑器 -->
          <MyEditor v-model="articleForm.content" v-else />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('articleForm')">提交</el-button>
          <el-button @click="onCancel">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  getArticleByUrl,
  uploadCover,
  getCategoryList,
  addArticle,
  updateOneArticle,
  getArticleDetail,
  getDraftDetail
} from '@/api/article'
import { isUrlValid } from '@/utils/validate'
export default {
  name: 'EditAddArticle',
  props: {
    type: {
      type: String,
      default: 'add'
    },
    is_draft: {
      type: Boolean
    }
  },
  data() {
    return {
      address: '',
      formData: null,
      categoryOptions: [],
      articleForm: {
        cover: '',
        title: '',
        content: '',
        category: '',
        is_draft: false,
        is_markdown: true
      },
      rules: {
        title: [{ required: true, message: '请输入文章名称', trigger: 'blur' }],
        content: [
          {
            validator: (rule, value, callback) => {
              if (!value || value.trim() === '<p><br></p>') {
                callback(new Error('文章内容不能为空'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        category: [{ required: true, message: '请选择文章类型', trigger: 'change' }]
      },
      is_draftOptions: [
        { key: 1, label: '是', value: true },
        { key: 2, label: '否', value: false }
      ]
    }
  },
  created() {
    this.getUserCategoryList()
  },
  computed: {
    id() {
      return this.$route.params.id
    }
  },
  watch: {
    id: {
      immediate: true,
      deep: true,
      handler(newValue) {
        if (this.type === 'edit' && !!newValue) {
          this.getEditInfo(newValue)
        }
      }
    },
    'articleForm.is_markdown': {
      handler() {
        if (this.type === 'add') {
          this.articleForm.content = ''
        }
      }
    },
    'articleForm.content': {
      handler(newValue) {
        if (newValue) {
          this.$refs.articleForm.clearValidate('content')
        }
      }
    }
  },
  methods: {
    // 爬虫获取文章
    async getArticle() {
      try {
        if (!this.address || !isUrlValid(this.address)) {
          this.$message({
            type: 'error',
            message: '请输入文章地址,目前只支持juejin,csdn,weixin公众号文章',
            offset: 80
          })
          return false
        }
        const params = this.address
        const {
          data: { content, title }
        } = await getArticleByUrl({ url: params })
        this.articleForm.content = content
        this.articleForm.title = title
      } catch (error) {
        console.log(error)
        this.$message({
          type: 'error',
          message: '获取文章失败,请检查地址是否正确',
          offset: 80
        })
      }
    },
    // 上传文章封面
    async addCover() {
      const formData = this.formData
      try {
        const res = await uploadCover(formData)
        if (res.code === 200) {
          this.articleForm.cover = res.data.imgUrl
          this.$message({
            type: 'success',
            message: '文章封面上传成功',
            offset: 80
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 上传图片之前的校验
    beforeUpload(file) {
      const type = file.name.substring(file.name.lastIndexOf('.') + 1)
      const typeInfo = ['jpg', 'png', 'jpeg']
      if (!typeInfo.includes(type)) {
        this.$message({
          type: 'error',
          message: '上传图片格式不正确,请上传jpg、png、jpeg格式的图片',
          offset: 80
        })
        return false
      }
      if (file.size / 1024 > 2048) {
        this.$message({
          type: 'error',
          message: '上传图片大小不能超过2M',
          offset: 80
        })
        return false
      }
      const formData = new FormData()
      formData.append('files', file)
      this.formData = formData
    },
    // 获取分类列表
    async getUserCategoryList() {
      try {
        const res = await getCategoryList()
        if (res.code === 200) {
          this.categoryOptions = res.data
        }
      } catch (error) {
        console.log(error)
      }
    },
    async getEditInfo(id) {
      try {
        const {
          data: {
            title,
            cover,
            content,
            is_draft,
            is_markdown,
            category: { _id }
          }
        } = !this.is_draft ? await getArticleDetail(id) : await getDraftDetail(id)
        this.articleForm = { title, cover, content, category: _id, is_draft, is_markdown }
      } catch (error) {
        console.log('error: ', error)
      }
    },
    // 提交表单
    onSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const articleForm = this.articleForm
          try {
            this.id ? await updateOneArticle(this.id, articleForm) : await addArticle(articleForm)
            this.$message({
              type: 'success',
              message: this.id ? '文章修改成功' : '文章添加成功'
            })
            this.jump()
          } catch (error) {
            console.log('error: ', error)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 跳转
    jump() {
      if (!this.is_draft) {
        this.$router.replace({ path: '/user/' + this.user_id })
      } else {
        this.$router.replace({ path: '/user/' + this.user_id + '/draft' })
      }
    },
    // 返回
    onCancel() {
      this.jump()
    }
  }
}
</script>

<style lang="scss" scoped>
.article {
  padding: 20px 50px 20px 0;
  background-color: #fff;
  .btn {
    margin-left: 20px;
    margin-right: 5px;
  }
}
</style>
